package org.forum.chat.serverpoint.Message;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageDecoder implements Decoder.Text<Message>{
	
	Logger logger = LoggerFactory.getLogger(MessageDecoder.class);

	@Override
	public void destroy() {
		
	}

	@Override
	public void init(EndpointConfig config) {
		
	}

	@Override
	public Message decode(String message) throws DecodeException {
		JSONObject jsonObject = new JSONObject().getJSONObject(message);
		if(logger.isDebugEnabled()){
			logger.debug(" 解析json对象成功：" + "\n" + jsonObject.toString());
		}
		String type = (String) jsonObject.get("type");
		if(type.equals(Message.FINDCONTACTSMESSAGE)){
			if(logger.isDebugEnabled()){
				logger.debug("此功能暂未给予实现");
			}
			return null;
		}
		else if(type.equals(Message.CHATMESSAGE)){
			ChatMessage chatMessage = new ChatMessage(jsonObject.getString("type"));
			chatMessage.setContent(jsonObject.getString("content"));
			chatMessage.setSender(jsonObject.getString("sender"));
			chatMessage.setTo(jsonObject.getString("to"));
			return chatMessage;
		}
		else if(type.equals(Message.LOGOUTMESSAGE)){
			if(logger.isDebugEnabled()){
				logger.debug("此功能暂未给予实现");
			}
		}
		else {
			if(logger.isDebugEnabled()){
				logger.debug("出现错误：" + "信息类型不对");
			}
		}
		return null;
	}

	@Override
	public boolean willDecode(String arg0) {
		return true;
	}

}
